package com.message.factory;

import com.constant.MessageType;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.message.*;
import com.message.resp.*;

import java.nio.charset.StandardCharsets;

public class MessageDeSerializerFactory implements MessageDeSerializerAbstractFactory{

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    }

    public Message readMessage(byte[] bytesJsonStr, byte messageType) {
        try {
            String JsonStr = new String(bytesJsonStr, StandardCharsets.UTF_8);
            if (messageType == MessageType.LOGIN_REQUEST) {

                return OBJECT_MAPPER.readValue(JsonStr, LoginReqMessage.class);

            } else if (messageType == MessageType.LOGIN_RESPONSE) {

                return OBJECT_MAPPER.readValue(JsonStr, LoginResp.class);

            } else if (messageType == MessageType.CHAT_REQUEST) {
                return OBJECT_MAPPER.readValue(JsonStr, ChatReqMessage.class);

            }else if(messageType == MessageType.CHAT_RESPONSE){
                return OBJECT_MAPPER.readValue(JsonStr, ChatResp.class);

            }else if(messageType == MessageType.GROUP_CREATE_REQUEST){

                return OBJECT_MAPPER.readValue(JsonStr, ChatGroupCreateMessage.class);

            }else if(messageType == MessageType.GROUP_CREATE_RESPONSE){

                return OBJECT_MAPPER.readValue(JsonStr, ChatGroupCreateResp.class);
            }else if(messageType == MessageType.GROUP_CHAT_REQUEST){

                return OBJECT_MAPPER.readValue(JsonStr, GroupChatReqMessage.class);
            }else if(messageType == MessageType.GROUP_CHAT_RESPONSE){

                return OBJECT_MAPPER.readValue(JsonStr, GroupChatResp.class);

            }else if(messageType == MessageType.GROUP_QUIT_REQUEST){

                return OBJECT_MAPPER.readValue(JsonStr, ExitGroupChatReqMessage.class);
            }else if(messageType == MessageType.GROUP_QUIT_RESPONSE){

                return OBJECT_MAPPER.readValue(JsonStr, ExitGroupResp.class);
            }
            else if(messageType == MessageType.EXIT_SERVER){

                return OBJECT_MAPPER.readValue(JsonStr, ChatLoginOutMessage.class);
            }else if(messageType==MessageType.PING_REQ){
                return OBJECT_MAPPER.readValue(JsonStr,PingMessage.class);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return new DefaultMessage() {
            @Override
            public int getMessageType() {
                return 0;
            }
        };
    }
}
